﻿using System;
using System.Linq;
using Core.Security;
using DataEntities;
using DataProvider;
using SQLDataProvider;

namespace BusinessServices
{
    public class SettingService
    {
        private readonly IBaseRepository<Setting> _settingRepository;

        public SettingService()
        {
            _settingRepository = new BaseRepository<Setting>();
        }

        /// <summary>
        /// 获取自定义设置
        /// </summary>
        /// <returns></returns>
        public Setting Get()
        {
            var list = _settingRepository.GetAll(s => true);
            if (list.Count == 0)
            {
                return new Setting();
            }
            return list.First();
        }

        /// <summary>
        /// 更新用户设置
        /// </summary>
        /// <param name="update">包含更改设置的委托,在此委托中进行更改操作</param>
        public Setting Update(Action<Setting> update)
        {
            return _settingRepository.Update(s => s.Id == 1, update);
        }

        /// <summary>
        /// 验证登录密码
        /// </summary>
        /// <param name="pwd">用户密码</param>
        public bool ValidatePwd(string pwd)
        {
            var setting = this.Get();
            if (string.IsNullOrEmpty(setting.Pwd))
            {
                return true;
            }
            pwd = Md5.GetMd5Hash(pwd);
            return string.Equals(setting.Pwd, pwd);
        }
    }
}
